<?php
namespace app\api\command;

use think\App;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Workerman\Worker;
class HttpServer extends Command
{

    private $server ;


    protected function configure()
    {
        $this->setName('HttpServer')->setDescription('http server');

        $this->addArgument('start',null,'','start');
    }

    protected function execute(Input $input, Output $output)
    {
        /* 永不超时 */
        ini_set('max_execution_time', 0);
        $date = $input->getArgument('start');
        $this->doCron($date);
    }


    public function doCron($data){

        $this->server = new Worker('http://0.0.0.0:1235');

        // 启动4个进程对外提供服务
        $this->server->count = 4;
        // 设置回调
        foreach (['onWorkerStart', 'onConnect', 'onMessage', 'onClose', 'onError', 'onBufferFull', 'onBufferDrain', 'onWorkerStop', 'onWorkerReload'] as $event) {
            if (method_exists($this, $event)) {
                $this->server->$event = [$this, $event];
            }
        }

        // 运行worker
        Worker::runAll();

    }

    public function onWorkerStart($worker)
    {
        error_reporting(E_ERROR | E_PARSE );
    }


    // 处理客户端连接
    public function onConnect($connection)
    {

    }

    // 处理客户端消息
    public function onMessage($connection, $data)
    {

        $_SERVER = [];
        //server信息
        if (isset($data['server'])) {

            foreach ($data['server'] as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        //header头信息
        if (isset($data['header'])) {
            foreach ($data['header'] as $k => $v) {
                $_SERVER[strtoupper($k)] = $v;
            }
        }

        $_GET = [];
        //get请求
        if (isset($data['get'])) {
            foreach ($data['get'] as $k => $v) {
                $_GET[$k] = $v;
            }
        }

        $_POST = [];
        //post请求
        if (isset($data['post'])) {
            foreach ($data['post'] as $k => $v) {
                $_POST[$k] = $v;
            }
        }

        $_FILES = [];
        //文件请求
        if (isset($data->files)) {
            foreach ($data->files as $k => $v) {
                $_FILES[$k] = $v;
            }
        }

        $_COOKIE = [];
        //cookies请求
        if (isset($data->cookie)) {
            foreach ($data->cookie as $k => $v) {
                $_COOKIE[$k] = $v;
            }
        }

        ob_start();//启用缓存区
        App::run()->send();
        $res = ob_get_contents();//获取缓存区的内容
        ob_end_clean();//清除缓存区

        //输出缓存区域的内容
        $connection->send($res);
    }

    // 处理客户端断开
    public function onClose($connection)
    {

    }




}